//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Windows;
using System.Windows.Documents;
using OpenLS.Core.Serialization;

namespace OpenLS.Drawing
{
    public abstract class RunBase : IOfficeXmlSerializable
    {
        internal abstract Inline Inline { get; }

        #region IOfficeXmlSerializable Members

        void IOfficeXmlSerializable.ReadXml(ReadContext context)
        {
            ReadXmlCore(context);
        }

        void IOfficeXmlSerializable.WriteXml(WriteContext context)
        {
            WriteXmlCore(context);
        }

        #endregion

        internal abstract void ReadXmlCore(ReadContext context);

        internal abstract void WriteXmlCore(WriteContext context);

        internal static RunBase FromInline(Inline inline)
        {
            if (inline is Run)
            {
                Run run = (Run) inline;
                var enumerator = run.GetLocalValueEnumerator();
                var result =  new RegularTextRun(run.Text);
                while (enumerator.MoveNext())
                {
                    var current = enumerator.Current;
                    if (current.Property == TextElement.FontWeightProperty)
                        result.EnsureTextCharacterProperties().Bold = run.FontWeight == FontWeights.Bold;                        
                    if (current.Property == TextElement.FontStyleProperty)
                        result.EnsureTextCharacterProperties().Italic = run.FontStyle == FontStyles.Italic;                        
                    if (current.Property == TextElement.FontSizeProperty)
                        result.EnsureTextCharacterProperties().FontSize = run.FontSize;                        
                    if (current.Property == TextElement.FontFamilyProperty)
                        result.EnsureTextCharacterProperties().Latin = run.FontFamily; 
                    if (current.Property == System.Windows.Documents.Inline.TextDecorationsProperty)
                    {
                        var decorations = run.TextDecorations;
                        foreach (var d in decorations)
                        {
                            
                            result.EnsureTextCharacterProperties().Underline = TextUnderlineType.Single;
                        }
                    }
                }
                return result;
            }
            if (inline is LineBreak)
                return new TextLineBreak();
            return null;
        }
    }
}